<template>
  <vxe-modal
    :title="$t('common.button.update', '修改')"
    v-model="show"
    :loading="loading"
    :mask="false"
    :lock-view="false"
    width="1024px"
    height="750px"
    destroy-on-close
    show-zoom
    remember
    resize
    show-footer
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="labelWidth"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" :name="0">
          <el-row>
            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.username', '用户名')"
                prop="username"
                tooltipContent="$t('请输入由字母数字下划线组成的4-20位的字符')"
              >
                <el-input
                  v-model="formData.username"
                  :placeholder="$p('menu.admin.user.field.username', '用户名')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.dept_id', '部门')"
                prop="dept_id"
              >
                <el-tree-select
                  v-model="formData.dept_id"
                  :data="options['dept_id'] || []"
                  check-strictly
                  show-checkbox
                  default-expand-all
                  :multiple="false"
                  :placeholder="$p('menu.admin.user.field.dept_id', '部门')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.role_ids', '角色')"
                prop="role_ids"
              >
                <el-select
                  v-model="formData.role_ids"
                  :multiple="true"
                  :placeholder="$p('menu.admin.user.field.role_ids', '角色')"
                >
                  <el-option
                    v-for="item in options['role_ids']"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('common.field.remark', '备注')"
                prop="remark"
              >
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :row="6"
                  :placeholder="$p('common.field.remark', '备注')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('common.field.sort', '排序')"
                prop="sort"
              >
                <el-input-number
                  v-model="formData.sort"
                  :placeholder="$p('common.field.sort', '排序')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('common.field.status', '状态')"
                prop="status"
              >
                <ra-dict-switch
                  v-model="formData.status"
                  code="switch_options"
                />
              </el-form-item-plus>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="个人信息" :name="1">
          <el-row>
            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.email', '邮箱')"
                prop="email"
              >
                <el-input
                  v-model="formData.email"
                  :placeholder="$p('menu.admin.user.field.email', '邮箱')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.mobile', '电话')"
                prop="mobile"
              >
                <el-input
                  v-model="formData.mobile"
                  :placeholder="$p('menu.admin.user.field.mobile', '电话')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.realname', '姓名')"
                prop="realname"
              >
                <el-input
                  v-model="formData.realname"
                  :placeholder="$p('menu.admin.user.field.realname', '姓名')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.nickname', '昵称')"
                prop="nickname"
              >
                <el-input
                  v-model="formData.nickname"
                  :placeholder="$p('menu.admin.user.field.nickname', '昵称')"
                />
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.avatar', '头像')"
                prop="avatar"
              >
                <ra-upload-card
                  v-model="formData.avatar"
                  :multiple="false"
                  :placeholder="$p('menu.admin.user.field.avatar', '头像')"
                ></ra-upload-card>
              </el-form-item-plus>
            </el-col>

            <el-col :span="span">
              <el-form-item-plus
                :label="$t('menu.admin.user.field.gender', '性别')"
                prop="gender"
              >
                <ra-dict-select
                  type="radio"
                  v-model="formData.gender"
                  code="gender_options"
                >
                </ra-dict-select>
              </el-form-item-plus>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <!-- 结束 -->
    </el-form>

    <template #footer>
      <el-button type="warning" @click="handleCancel">
        {{ $t('common.action.cancel', '取消') }}
      </el-button>
      <el-button type="info" @click="handleReset">
        {{ $t('common.action.reset', '重置') }}
      </el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="loading">
        {{ $t('common.action.confirm', '确定') }}
      </el-button>
    </template>
  </vxe-modal>
</template>
<script setup>
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

defineOptions({
  name: 'Update',
  inheritAttrs: false,
});

const props = defineProps({
  api: {
    type: Object,
    required: true,
    validator: (value) => {
      return (
        typeof value.update === 'function' &&
        typeof value.getFormData === 'function'
      );
    },
  },
  options: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['reload']);

// 响应式数据
const loading = ref(false);
const show = ref(false);
const activeTab = ref(0);
const labelWidth = ref('120px');
const span = 24;
const formRef = ref();
const currentId = ref(null);

// 表单数据
const defaultFormData = {
  username: null,
  email: null,
  mobile: null,
  password: null,
  realname: null,
  nickname: null,
  avatar: null,
  gender: null,
  dept_name: null,
  dept_id: null,
  role_ids: [],
  role_names: null,
  remark: null,
  sort: null,
  status: null,
};
const formData = reactive({ ...defaultFormData });

// 表单验证规则
const formRules = reactive({
  username: [
    {
      pattern: /^[a-zA-Z0-9_-]{4,20}$/,
      message: '请检查输入的字符格式，是否符合用户名(英文字符)的格式要求 。',
      trigger: 'blur',
    },
  ],

  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message:
        '请检查输入的字符格式，是否符合/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/的格式要求 。',
      trigger: 'blur',
    },
  ],

  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请检查输入的字符格式，是否符合/^1[3-9]\d{9}$/的格式要求 。',
      trigger: 'blur',
    },
  ],
});

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(formData, defaultFormData);
};

// 表单验证
const validateForm = async () => {
  return await formRef.value?.validate();
};

// 加载用户数据
const loadUserData = async (id) => {
  loading.value = true;
  try {
    const { data } = await props.api.getFormData({ id: id });

    Object.assign(formData, data);
    currentId.value = id;
    await nextTick();
    formRef.value?.clearValidate();
  } catch (error) {
    console.error('Error loading data:', error);
    throw error;
  } finally {
    loading.value = false;
  }
};

// 提交处理
const handleSubmit = async () => {
  try {
    await validateForm();
    loading.value = true;
    await props.api.update({ ...toRaw(formData) });
    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error('Error in add operation:', error);
  } finally {
    loading.value = false;
  }
};

// 取消处理
const handleCancel = () => {
  show.value = false;
};

// 重置处理
const handleReset = async () => {
  if (currentId.value) {
    await loadUserData(currentId.value);
  } else {
    resetForm();
  }
};

// 显示模态框
const showModal = async (id) => {
  if (!id) {
    console.error('User ID is required for edit mode');
    return;
  }

  try {
    await loadUserData(id);
    show.value = true;
  } catch (error) {
    console.error('Failed to load user data:', error);
  }
};

defineExpose({
  show: showModal,
});
</script>
<style lang="scss" scoped></style>
